package com.surprise.ods.aliyun;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

/**
 * UploadObject.java
 * @author nick
 * @since 2015年7月29日
 */
public class UploadObject {

	public static void test1() throws IOException {
		String filename = "dog.png";
		String ak = "9dE65juy1oCUheiZ";
		String sk = "Ct5r5x7UWSVIuxwnrxsINzv8LTikJ5";
		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

		OSSClient client = new OSSClient(endpoint, ak, sk);
		List<Bucket> buckets = client.listBuckets();

		// 遍历Bucket
		File file = new File("E:\\Picture\\a.jpg");
		InputStream io = FileUtils.openInputStream(file);

		ObjectMetadata meta = new ObjectMetadata();
		// 必须设置ContentLength
		meta.setContentLength(file.length());
		meta.setContentType("image/jpeg");

		// 上传Object
		PutObjectResult result = client.putObject("surprise-oss", "pig/"+filename, io,
				meta);
		System.out.println(result.getETag());
	}

	public static void test2() throws IOException {
		String accessKeyId = "9dE65juy1oCUheiZ";
		String accessKeySecret = "Ct5r5x7UWSVIuxwnrxsINzv8LTikJ5";
		// 以杭州为例
		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// list all buckets
		List<Bucket> buckets = client.listBuckets();
		// 遍历Bucket
		for (Bucket bucket : buckets) {
			System.out.println(bucket.getName());
		}

		ObjectListing listing = client.listObjects("surprise-oss");
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			System.out.println(objectSummary.getKey());
		}
	}

	public static void main(String[] args) throws IOException {
		test1();
	}
}
